package com.financing.platform.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.financing.platform.common.Pager;
import com.financing.platform.vo.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.platform.activities.ActivitiesBusinessObject;
import com.financing.platform.dao.IActivitieGiftDao;
import com.financing.platform.dao.ICorpProjectDao;
import com.financing.platform.dao.IFaUserDao;
import com.financing.platform.dao.IMessageDao;
import com.financing.platform.dao.IMessageMailDao;
import com.financing.platform.dao.IMessageNoteDao;
import com.financing.platform.dao.IMessageSmsDao;
import com.financing.platform.dao.IOrderDao;
import com.financing.platform.dao.IProductOrderDataDao;
import com.financing.platform.dao.IProjectAnnualRevenueDao;
import com.financing.platform.dao.IProjectDao;
import com.financing.platform.dao.IUserAccountDao;
import com.financing.platform.dao.impl.ProjectDaoImpl;
import com.financing.platform.dto.ActivitieGiftDTO;
import com.financing.platform.dto.CorpProjectDTO;
import com.financing.platform.dto.FaUserDTO;
import com.financing.platform.dto.FpProjectRabate;
import com.financing.platform.dto.MessageDTO;
import com.financing.platform.dto.MessageNoteDTO;
import com.financing.platform.dto.MessageSmsDTO;
import com.financing.platform.dto.OrderDTO;
import com.financing.platform.dto.OrderFlowDTO;
import com.financing.platform.dto.ProductAnnualRevenueDTO;
import com.financing.platform.dto.ProductAttachmentDTO;
import com.financing.platform.dto.ProductDetailPageDTO;
import com.financing.platform.dto.ProductOrderDataDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.dto.ProjectExpandDTO;
import com.financing.platform.service.IActivitesService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.util.Dict;
import com.financing.platform.util.MessageUtil;
import com.financing.platform.util.StringUtil;

@Service("projectServiceImpl")
public class ProjectServiceImpl extends BaseServiceImpl implements
		IProjectService {

	@Autowired
	private IProjectDao projectDaoImpl;
	
	@Autowired
	private IOrderDao orderDaoImpl;
	
	@Autowired
	private IMessageDao messageDaoImpl;
	
	@Autowired
	private IMessageNoteDao messageNoteDaoImpl;
	
	@Autowired
	private IMessageSmsDao messageSmsDaoImpl;
	
	@Autowired
	private IMessageMailDao messageMailDaoImpl;
	
	@Autowired
	private IFaUserDao faUserDaoImpl;
	
	@Autowired
	private ICorpProjectDao corpProjectDaoImpl;
	
	@Autowired
	private IActivitieGiftDao activitieGiftDaoImpl;
	
	@Autowired
	private IUserAccountDao userAccountDaoImpl;
	@Autowired
	private IProjectAnnualRevenueDao projectAnnualRevenueDaoImpl;
	@Autowired
	private IActivitesService activitesServiceImpl;
	@Autowired
	private MailSenderService mailSenderService;
	
    @Autowired
    private IProductOrderDataDao productOrderDataDao;

    private Logger logger=Logger.getLogger(ProjectServiceImpl.class);
	
	public List<ProjectDTO> queryAllProject(ProjectDTO projectDTO) {
		return projectDaoImpl.getProjectList(projectDTO);
	}

	public ProjectDTO queryProject(ProjectDTO projectDTO) {
		ProjectDTO pt= projectDaoImpl.searchProjectByIdOrCode(projectDTO);
		ProductOrderDataDTO productOrderDataDto=new ProductOrderDataDTO();
		productOrderDataDto.setpId(pt.getId());
		productOrderDataDto.setpType(pt.getpType());
		try {
			String tjzls=productOrderDataDao.queryProductOrderData(productOrderDataDto);
			if(StringUtils.isNotBlank(tjzls)) pt.setTjzls(tjzls.replace("0","").replace("1,2,3,4", "1"));
		} catch (SQLException e) {
			logger.error("queryProductOrderData error",e);
		}
		return pt;
	}

	
	@Transactional(rollbackFor=SQLException.class)
	public int updateProject(ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO) throws SQLException{
		ProjectDTO projectTmp = new ProjectDTO();
		projectTmp.setId(projectDTO.getId());
		projectTmp = projectDaoImpl.searchProjectByIdOrCode(projectTmp);
		if(Dict.pPublicStatus_Yes_public.equals(projectDTO.getpPublicStatus())){
			if(!Dict.pPublicStatus_undercarriage.equals(projectTmp.getStatus()) &&  !Dict.pProductStatus_need_public.equals(projectTmp.getStatus())&&!Dict.pProductStatus_need_public5.equals(projectTmp.getStatus())){
				return 0;
			}
//			CorpProjectDTO corpProject = corpProjectDaoImpl.queryCorpProject(projectDTO.getId());
			
//			if(corpProject != null && Dict.project_sale_type_own.equals(corpProject.getFpProjectCorpType()) && Dict.project_own_corp != corpProject.getFpCorpId()){
//				Integer corpId = corpProject.getFpCorpId();
//				sendMessage(projectTmp,faUserDaoImpl.getAllFaId(corpId),"productPublish");
//			}else{
//				sendMessage(projectTmp,faUserDaoImpl.getAllFaId(null),"productPublish");
//			}
		}
		// TODO
		// 插入流水判断
		log.info("========================flow panduan1===========================================");
		projectTmp = new ProjectDTO();
		projectTmp.setId(projectDTO.getId());
		projectTmp = projectDaoImpl.searchProjectById(projectDTO);
		log.info(projectDTO.getpPublicStatus());
		log.info(projectTmp.getpPublicStatus());
		if(null != projectDTO.getpPublicStatus() &&projectDTO.getpPublicStatus().equals("2") && null != projectTmp.getpPublicStatus() && !projectDTO.getpPublicStatus().equals(projectTmp.getpPublicStatus())){
			// 产品上线
			log.info("sssssssssssssssssssssssssssssssssssss");
			projectTmp.setpPublicStatus("2");
			this.addProjectFlow(projectTmp, 1);
		}
		log.info("========================flow panduan1===========================================");
		int i = projectDaoImpl.updateProject(projectDTO);
		if(projectExpandDTO!=null){
			//修改产品扩展
			projectDaoImpl.updateProjectExpand(projectExpandDTO);
			log.info(" updateProjectExpand success!");

		}
		//募集進度是否修改  
		if (!compareBigDecimal(projectDTO.getpIssuingScale(),projectTmp.getpIssuingScale()) ||!compareString(projectTmp.getpPeriods(),projectDTO.getpPeriods())
				|| !compareString(projectDTO.getpRecruitmentSummary(),projectTmp.getpRecruitmentSummary())
				||!compareBigDecimal(projectDTO.getpAllSubscriptionAmount(),projectTmp.getpAllSubscriptionAmount())) {
			// 记录更新进度日志
			try {
				projectDaoImpl.addForegroundProductLog(projectTmp);
			} catch (Exception e) {
				log.error("addForegroundProductLog error ", e);
			}
		}
		
		return i;
	}

	@Override
	public int updateProject(ProjectDTO projectDTO) throws SQLException {
		return projectDaoImpl.updateProject(projectDTO);
	}

	public boolean compareBigDecimal(BigDecimal a,BigDecimal b){
		a=a==null?new BigDecimal(0):a;
		b=b==null?new BigDecimal(0):b;
		return a.compareTo(b)==0;
	}
	public boolean compareString(String a,String b){
		a=StringUtils.isBlank(a)?"":a;
		b=StringUtils.isBlank(b)?"":b;
		return a.equals(b);
	}
	
	@Transactional(rollbackFor=SQLException.class)
	public int updateProjectFull(ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO) throws SQLException{
		
		if(Dict.pPublicStatus_Yes_public.equals(projectDTO.getpPublicStatus())){
			
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setId(projectDTO.getId());
			projectTmp = projectDaoImpl.searchProjectByIdOrCode(projectTmp);
			
			if(!Dict.pProductStatus_need_public.equals(projectTmp.getStatus())){
				return 0;
			}
			
//			CorpProjectDTO corpProject = corpProjectDaoImpl.queryCorpProject(projectDTO.getId());
			
//			if(corpProject != null && Dict.project_sale_type_own.equals(corpProject.getFpProjectCorpType()) && Dict.project_own_corp != corpProject.getFpCorpId()){
//				Integer corpId = corpProject.getFpCorpId();
//				sendMessage(projectTmp,faUserDaoImpl.getAllFaId(corpId),"productPublish");
//			}else{
//				sendMessage(projectTmp,faUserDaoImpl.getAllFaId(null),"productPublish");
//			}
		}
		//修复-错误 #1137: 后台-产品结束金额未填写保存显示原募集规模后再次修改募集规模，结束金额仍然显示原来的
		ProjectDTO bean = new ProjectDTO();
		bean.setId(projectDTO.getId());
		bean = projectDaoImpl.searchProjectByIdOrCode(bean);
		if(bean != null && bean.getpIssuingScale()!=null && projectDTO.getpIssuingScale() !=null && bean.getpIssuingScale().compareTo(projectDTO.getpIssuingScale())!=0){
			log.info(" ############## pIssuingScale change ####### p_id:"+projectDTO.getId());
			Map<String,Object> map = new HashMap<String,Object> ();
			map.put("newAmount", projectDTO.getpIssuingScale());
			map.put("oldAmount", bean.getpIssuingScale());
			map.put("pid", projectDTO.getId());
			map.put("updateBy", projectDTO.getUpdateBy());
			projectAnnualRevenueDaoImpl.updateProjectAnnualRevenueByendAmount(map);
		}
		
		//图片类型(01:身份证正面；02：身份证反面；03：银行卡；04：打款凭条；05：签字页；06：合同封面；07手持签字页和合同封面；08：其他)
		ProductOrderDataDTO productOrderDataDto=new ProductOrderDataDTO();
		productOrderDataDto.setpType(projectDTO.getpType());
		productOrderDataDto.setpId(projectDTO.getId());
		productOrderDataDto.setUpdateBy(projectDTO.getUpdateBy());
		
		//删除所有该产品附件要求
		productOrderDataDao.delProductOrderData(productOrderDataDto);

		productOrderDataDto.setCreateBy(projectDTO.getUpdateBy());

		insertOrderData(projectDTO.getTjzls(), productOrderDataDto);
		
		int isExist = projectDaoImpl.selectProjectExpand(projectDTO.getId());
		
		if(projectExpandDTO!=null){
			  if(isExist > 0){
					//修改产品扩展
					projectDaoImpl.updateProjectExpand(projectExpandDTO);
					log.info(" updateProjectExpand success!");
				}else{
					//新增产品扩展信息
					projectDaoImpl.addProjectExpand(projectExpandDTO);
					log.info("add ProjectExpand success!");
			}
		}
		
		return projectDaoImpl.updateProjectFull(projectDTO);
	}
	public int updateProductAttachment(List<ProductAttachmentDTO> productAttachmentDTOList,int productId) throws SQLException {
		projectDaoImpl.deleteProductAttachment(productId);
		for(ProductAttachmentDTO productAttachmentDTO:productAttachmentDTOList){
			productAttachmentDTO.setpId(productId);
			projectDaoImpl.insertProductAttachment(productAttachmentDTO);
		}
		return productAttachmentDTOList.size();
	}

	@Transactional(rollbackFor=Exception.class)
	public int addProject(ProjectDTO projectDTO,CorpProjectDTO corpProjectDTO,List<ProductAttachmentDTO> productAttachmentDTOList) throws SQLException {
		
		//赋值产品code
		projectDTO.setpCode(projectDaoImpl.queryUUID());
		//分期产品，pLinkCode相同
		if(projectDTO.getpLinkCode()!=null){
			//查询 pLinkCode 产品是否存在
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setpLinkCode(projectDTO.getpLinkCode());
			List<ProjectDTO> projectList =  projectDaoImpl.getProjectList(projectTmp);
			if(projectList != null && projectList.get(0) != null){
			} else{
				log.error(" getpCode is not null");
				projectDTO.setpLinkCode(projectDTO.getpCode());
			}
		}else{
			projectDTO.setpLinkCode(projectDTO.getpCode());
		}
		
		int projectId = projectDaoImpl.addProject(projectDTO);
		corpProjectDTO.setFpProjectId(projectId);
		corpProjectDaoImpl.add(corpProjectDTO);
		
		for(ProductAttachmentDTO productAttachmentDTO:productAttachmentDTOList){
			productAttachmentDTO.setpId(projectId);
			productAttachmentDTO.setCreateBy(projectDTO.getCreateBy());
			productAttachmentDTO.setCreateDate(projectDTO.getCreateDate());
			productAttachmentDTO.setUpdateBy(projectDTO.getUpdateBy());
			productAttachmentDTO.setUpdateDate(projectDTO.getUpdateDate());
			projectDaoImpl.insertProductAttachment(productAttachmentDTO);
		}

		return projectId;
	}
	
	@Transactional(rollbackFor=Exception.class)
	public int projectSet(ProjectDTO project) throws SQLException {
		
		// TODO
		// 插入流水判断
		log.info("========================flow panduan3===========================================");
		ProjectDTO projectTmp1 = new ProjectDTO();
		projectTmp1.setId(project.getId());
		projectTmp1 = projectDaoImpl.searchProjectById(project);
		log.info(project.getpEstablishmentTime());
		log.info(projectTmp1.getpEstablishmentTime());
		if(null != project.getpEstablishmentTime() && null == projectTmp1.getpEstablishmentTime()){
			// 是否是产品成立
			log.info("cccccccccccccccccccccccccccccccc");
			projectTmp1.setpEstablishmentTime(project.getpEstablishmentTime());
			this.addProjectFlow(projectTmp1, 3);
		}
		log.info("========================flow panduan3===========================================");
		int result = updateProject(project,null);
		OrderDTO orderDTO = new OrderDTO();
		orderDTO.setUpdateBy(project.getUpdateBy());
		orderDTO.setUpdateDate(project.getUpdateDate());
		
		orderDTO.setoProjectId(project.getId());
		orderDTO.setoStatus(Dict.order_status_product_set);
		
		/**
		 * 更新订单状态
		 */
		orderDaoImpl.updateOrder(orderDTO); 
		//orderDaoImpl.orderCancel(orderDTO);
		
		/**
		 * 记录订单状态修改流水
		 */
		orderDTO.setoStatus(null);
		List<OrderDTO> orderList = orderDaoImpl.queryOrderList(orderDTO);
		
		OrderFlowDTO orderFlowDTO = new OrderFlowDTO();
		orderFlowDTO.setCreateBy(orderDTO.getUpdateBy());
		orderFlowDTO.setUpdateDate(new Date());
		orderFlowDTO.setCreateDate(new Date());
		orderFlowDTO.setUpdateBy(orderDTO.getUpdateBy());
		orderFlowDTO.setFlowDate(new Date());
		
		for(OrderDTO order : orderList){
			orderFlowDTO.setUpdateBy(orderDTO.getUpdateBy());
			orderFlowDTO.setOrderId(order.getId());
			orderFlowDTO.setoStatus(order.getoStatus());
			orderDaoImpl.addOrderFlow(orderFlowDTO);
			
			if(order.getoStatus() == Dict.order_status_product_set ){
				log.info("Begin open gift for FA:"+order.getoFAId());
				openGift(order.getoFAId(),orderDTO);
				log.info("End open gift for FA:"+order.getoFAId());
			}
		}
		
		ProjectDTO projectTmp = new ProjectDTO();
		projectTmp.setId(project.getId());
		projectTmp = projectDaoImpl.searchProjectByIdOrCode(projectTmp);
		try{
//			sendMessage(projectTmp,orderDaoImpl.queryNeedSendSMSFAId(orderDTO),"productSet");
		}catch(Exception e){
			log.error("send message error!",e);
		}
		
		
		//注入活动信息
		try {
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("projectDTO", project);
			map.put("updateInt", result);
			activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_Product_Found, map);
		} catch (Exception e) {
			log.error("updateProject ActivitiesJobExecutionObejct error", e);
		}
		return result;
	}
	
	private void sendMessage(ProjectDTO projectDTO,List<String> faIds,String productStatus) throws SQLException{
			//添加消息主体
			MessageDTO messageDTO = new MessageDTO();
			messageDTO.setProductId(projectDTO.getId());
			messageDTO.setCreateBy(projectDTO.getUpdateBy());
			messageDTO.setCreateDate(projectDTO.getUpdateDate());
			messageDTO.setUpdateBy(projectDTO.getUpdateBy());
			messageDTO.setUpdateDate(projectDTO.getUpdateDate());
			messageDTO.setStatus(Dict.status_normal);
			
			Map<String, Object> msgMap = new HashMap<String,Object>();
			msgMap.put("pName", projectDTO.getpName());
			
			if("productSet".equals(productStatus)){
				DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分SS秒");
				msgMap.put("pEstablishmentTime", df.format(projectDTO.getpEstablishmentTime()));
			}
			
			msgMap = MessageUtil.getMessage("product",productStatus, msgMap);
			
			messageDTO.setMsgTitle((String)msgMap.get(Dict.message_title));
			messageDTO.setMsgContent((String)msgMap.get(Dict.message_content));
			messageDTO.setMsgType(Dict.message_type_project);
			
			messageDTO.setPublicDate(projectDTO.getUpdateDate());
			messageDTO.setEndDate(StringUtil.rollDay(projectDTO.getUpdateDate(), 10));
			
			int messageId = messageDaoImpl.addMessage(messageDTO);
			
			for(String faId :faIds){
			//添加站内消息
			MessageNoteDTO messageNoteDTO = new MessageNoteDTO();
			messageNoteDTO.setCreateBy(projectDTO.getUpdateBy());
			messageNoteDTO.setCreateDate(projectDTO.getUpdateDate());
			messageNoteDTO.setUpdateBy(projectDTO.getUpdateBy());
			messageNoteDTO.setUpdateDate(projectDTO.getUpdateDate());
			messageNoteDTO.setFaId(faId);
			messageNoteDTO.setMsgId(messageId);
			messageNoteDTO.setMsgStatus(Dict.message_note_status);
			messageNoteDTO.setStatus(Dict.status_normal);
			
			messageNoteDaoImpl.addMessageNote(messageNoteDTO);
			
			//添加短信息
			MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
			messageSmsDTO.setCreateBy(messageDTO.getUpdateBy());
			messageSmsDTO.setUpdateBy(messageDTO.getUpdateBy());
			messageSmsDTO.setCreateDate(messageDTO.getUpdateDate());
			messageSmsDTO.setUpdateDate(messageDTO.getUpdateDate());
			messageSmsDTO.setFpSmsMessageId(messageId);
			messageSmsDTO.setFpSmsContent(messageDTO.getMsgContent());
			messageSmsDTO.setFpSmsSendType(Dict.message_type_now);
			messageSmsDTO.setStatus(Dict.status_normal);
			messageSmsDTO.setFpSmsSendStatus(Dict.message_status_not_send);
			
			FaUserDTO fauser = new FaUserDTO();
			fauser.setId(faId);
			
			//查询fa手机号码
			fauser = faUserDaoImpl.getFaUser(fauser);
			
			if(fauser!=null&& !StringUtil.isNullOrEmptyStr(fauser.getuMobile())){
				messageSmsDTO.setFpSmsRecivePhoneNo(fauser.getuMobile());
				
				//messageSmsDaoImpl.addMessageSms(messageSmsDTO);
			}
			
		}
	}

	public int updateAllSubscription(ProjectDTO projectDTO) throws SQLException {
		// TODO
		// 插入流水判断
		log.info("========================flow panduan2===========================================");
		ProjectDTO projectTmp = new ProjectDTO();
		projectTmp.setId(projectDTO.getId());
		projectTmp = projectDaoImpl.searchProjectById(projectDTO);
		log.info(projectDTO.getpAllSubscriptionAmount());
		log.info(projectTmp.getpAllSubscriptionAmount());
		if (null != projectDTO.getpAllSubscriptionAmount() && null != projectTmp.getpAllSubscriptionAmount() && !compareBigDecimal(projectDTO.getpAllSubscriptionAmount(), projectTmp.getpAllSubscriptionAmount())) {
			// 募集进度修改 插入产品流水 订阅通知、产品信息
			log.info("jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj");
			projectTmp.setpAllSubscriptionAmount(projectDTO.getpAllSubscriptionAmount());
			this.addProjectFlow(projectTmp, 2);
		}
		log.info("========================flow panduan2===========================================");
		return projectDaoImpl.updateAllSubscription(projectDTO);
	}

	public CorpProjectDTO queryCorpProject(int projectId) throws SQLException {
		return corpProjectDaoImpl.queryCorpProject(projectId);
	}
	
	public int deleteProject(int projectId) throws SQLException {
		projectDaoImpl.deleteProductAttachment(projectId);
		return projectDaoImpl.deleteProject(projectId);
	}
	
	/**
	 *
	 * @Title: openGift
	 * @Description: 开自己和邀请人的红包
	 * @param @param faId
	 * @param @param order
	 * @param @throws SQLException
	 * @return void
	 * @throws
	 */
	private void openGift(String faId,OrderDTO order) throws SQLException{
		List<ActivitieGiftDTO> activitieGiftList = activitieGiftDaoImpl.queryActivitieGiftList(faId);
		for(ActivitieGiftDTO activitieGiftDTO :activitieGiftList){
			activitieGiftDTO.setaStatus(Dict.activitieGiftOpen);
			activitieGiftDTO.setUpdateBy(order.getUpdateBy());
			activitieGiftDTO.setUpdateDate(order.getUpdateDate());
			activitieGiftDaoImpl.updateActivitieGift(activitieGiftDTO);
			
			log.info("open gift :" +activitieGiftDTO);
			
			userAccountDaoImpl.thawingAccountMount(activitieGiftDTO);
		}
	}

	public List<ProjectVO> projectListForPublish(ProjectDTO projectDTO)
			throws SQLException {
		List<ProjectVO> projectListForPublish = projectDaoImpl.projectListForPublish(projectDTO);
		
		//huqy注释 列表不展示扩展信息
//		if(projectListForPublish!=null&&projectListForPublish.size()>0){
//			for (int i = 0; i < projectListForPublish.size(); i++) {
//				 //产品的扩展信息
//				List<FpProjectRabate> rebateList = projectDaoImpl.getProductProfitRebateList(projectListForPublish.get(i).getId());
//				
//				projectListForPublish.get(i).setRebateList(rebateList);
//			}
//		}
		
		return projectListForPublish;
	}

	@Override
	public int projectListForPublishCount(ProjectDTO projectDTO)
			throws SQLException {
		return projectDaoImpl.projectListForPublishCount(projectDTO);
	}

	@Override
	public List<ProductAttachmentDTO> queryProductAttachments(Integer pId)
			throws SQLException {
		return projectDaoImpl.queryProductAttachments(pId);
	}

	@Override
	public ProductAttachmentDTO queryProductAttachmentsForId(Integer Id) throws SQLException {


		return projectDaoImpl.queryProductAttachmentsForId(Id);
	}

	@Override
	public List<ProjectSendConfirmEmailVO> queryProjectInfoByIds(Integer[] array)
			throws SQLException {
		return projectDaoImpl.queryProjectInfoByIds(array);
	}

	@Override
	public int addProject(ProjectDTO projectDTO, CorpProjectDTO corpProjectDTO,
			List<ProductAttachmentDTO> productAttachmentDTOList, String copyType,ProjectExpandDTO projectExpandDTO)
			throws SQLException {
		//赋值产品code
		projectDTO.setpCode(projectDaoImpl.queryUUID());
		ProjectDTO projectDTOInit = null;
		
		//分期产品，pLinkCode相同
		if(projectDTO.getpLinkCode()!=null){
			//查询 pLinkCode 产品是否存在
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setpCode(projectDTO.getpLinkCode());
			List<ProjectDTO> projectList =  projectDaoImpl.getProjectList(projectTmp);
			if(projectList != null && projectList.size()>0){
				projectDTOInit =  projectList.get(0);
			} else{
				log.error(" getpCode is not null");
				projectDTO.setpLinkCode(projectDTO.getpCode());
			}
		}else{
			projectDTO.setpLinkCode(projectDTO.getpCode());
		}
		
		int projectId = projectDaoImpl.addProject(projectDTO);
		corpProjectDTO.setFpProjectId(projectId);
		corpProjectDaoImpl.add(corpProjectDTO);
		
		for(ProductAttachmentDTO productAttachmentDTO:productAttachmentDTOList){
			productAttachmentDTO.setpId(projectId);
			productAttachmentDTO.setCreateBy(projectDTO.getCreateBy());
			productAttachmentDTO.setCreateDate(projectDTO.getCreateDate());
			productAttachmentDTO.setUpdateBy(projectDTO.getUpdateBy());
			productAttachmentDTO.setUpdateDate(projectDTO.getUpdateDate());
			projectDaoImpl.insertProductAttachment(productAttachmentDTO);
		}

		//pLinkCode 不为空，表示是复制产品，且表示有复制产品解析，需要邮件通知风控   
		if(projectDTO.getpLinkCode()!=null && projectDTOInit!=null && "01".equals(copyType)){
			log.info("发送邮件!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("pCode", projectDTO.getpCode());
			params.put("pName", projectDTO.getpName());
			params.put("pOldName", projectDTOInit.getpName());
			params.put("pOldCode", projectDTO.getpLinkCode());
			Map<String,Object> mailMap = MessageUtil.getMsgInfo("mailTemplate", "productCopy", params);
			//发送邮件
			
			MailContentDTO mail = new MailContentDTO();
			mail.setContext((String)mailMap.get(MessageUtil.KEY_CONTENT));
			mail.setRecAddress((String)mailMap.get("mailto"));
			mail.setCc((String)mailMap.get("cc"));
			mail.setSubject((String)mailMap.get(MessageUtil.KEY_TITLE));
			mail.setRequestTime(new Date());
			mailSenderService.send(mail);
		}
		
		//图片类型(01:身份证正面；02：身份证反面；03：银行卡；04：打款凭条；05：签字页；06：合同封面；07手持签字页和合同封面；08：其他)
		ProductOrderDataDTO productOrderDataDto=new ProductOrderDataDTO();
		productOrderDataDto.setpId(projectId);
		productOrderDataDto.setpType(projectDTO.getpType());
		//插入 产品需要的 附件
		if(projectDTO.getTjzls()!=null){
			productOrderDataDto.setCreateBy(projectDTO.getCreateBy());
			productOrderDataDto.setCreateDate(projectDTO.getCreateDate());
			productOrderDataDto.setUpdateBy(projectDTO.getUpdateBy());
			productOrderDataDto.setUpdateDate(projectDTO.getUpdateDate());
			
			insertOrderData(projectDTO.getTjzls(),productOrderDataDto);
		}else{
			logger.info("product not have att file");
		}
		//添加产品扩展信息
		projectExpandDTO.setpId(projectId);
		projectDaoImpl.addProjectExpand(projectExpandDTO);
		
		log.info("addProduct projectDaoImpl.addProjectExpand success");
		
		return projectId;
	}
	@Override
	@Transactional(rollbackFor=SQLException.class)
	public int addProduct(ProjectDTO projectDTO, ProjectExpandDTO projectExpandDTO, CorpProjectDTO corpProjectDTO,String copyType)
			throws SQLException {
		//赋值产品code
		projectDTO.setpCode(projectDaoImpl.queryUUID());
		ProjectDTO projectDTOInit = null;
		
		//分期产品，pLinkCode相同
		if(projectDTO.getpLinkCode()!=null){
			//查询 pLinkCode 产品是否存在
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setpCode(projectDTO.getpLinkCode());
			List<ProjectDTO> projectList =  projectDaoImpl.getProjectList(projectTmp);
			if(projectList != null && projectList.size()>0){
				projectDTOInit =  projectList.get(0);
			} else{
				log.error(" getpCode is not null");
				projectDTO.setpLinkCode(projectDTO.getpCode());
			}
		}else{
			projectDTO.setpLinkCode(projectDTO.getpCode());
		}
		
		int projectId = projectDaoImpl.addProject(projectDTO);
		log.info("addProduct projectDaoImpl.addProject success");
		
		corpProjectDTO.setFpProjectId(projectId);
		corpProjectDaoImpl.add(corpProjectDTO);
		log.info("addProduct corpProjectDaoImpl.add success");
		
		//pLinkCode 不为空，表示是复制产品，且表示有复制产品解析，需要邮件通知风控   
		if(projectDTO.getpLinkCode()!=null && projectDTOInit!=null && "01".equals(copyType)){
			log.info("发送邮件!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("pCode", projectDTO.getpCode());
			params.put("pName", projectDTO.getpName());
			params.put("pOldName", projectDTOInit.getpName());
			params.put("pOldCode", projectDTO.getpLinkCode());
			Map<String,Object> mailMap = MessageUtil.getMsgInfo("mailTemplate", "productCopy", params);
			//发送邮件
			
			MailContentDTO mail = new MailContentDTO();
			mail.setContext((String)mailMap.get(MessageUtil.KEY_CONTENT));
			mail.setRecAddress((String)mailMap.get("mailto"));
			mail.setCc((String)mailMap.get("cc"));
			mail.setSubject((String)mailMap.get(MessageUtil.KEY_TITLE));
			mail.setRequestTime(new Date());
			mailSenderService.send(mail);
		}
		
		//图片类型(01:身份证正面；02：身份证反面；03：银行卡；04：打款凭条；05：签字页；06：合同封面；07手持签字页和合同封面；08：其他)
		ProductOrderDataDTO productOrderDataDto=new ProductOrderDataDTO();
		productOrderDataDto.setpId(projectId);
		//productOrderDataDto产品类型(01:公募基金、02:信托、03：资管、04：有限合伙、05:私募、06：pevc)
		//product产品类型  01:私募基金、02:信托、03：资管、04：有限合伙、06：PE\VC
		productOrderDataDto.setpType(projectDTO.getpType());
		//插入 产品需要的 附件
		if(projectDTO.getTjzls()!=null){
			productOrderDataDto.setCreateBy(projectDTO.getCreateBy());
			productOrderDataDto.setCreateDate(projectDTO.getCreateDate());
			productOrderDataDto.setUpdateBy(projectDTO.getUpdateBy());
			productOrderDataDto.setUpdateDate(projectDTO.getUpdateDate());
			
			insertOrderData(projectDTO.getTjzls(),productOrderDataDto);
			log.error("addProduct insertOrderData success");
		}else{
			logger.info("product not have att file");
		}
		
		//添加产品扩展信息
		projectExpandDTO.setpId(projectId);
		projectDaoImpl.addProjectExpand(projectExpandDTO);
		log.info("addProduct projectDaoImpl.addProjectExpand success");
		
		return projectId;
	}
	//插入 产品需要的 附件
	public void insertOrderData(String tjzls,ProductOrderDataDTO productOrderDataDto) throws SQLException {
		if(StringUtils.isNotBlank(tjzls)){
			for (int x = 0; x < tjzls.split(",").length; x++) {
				if(StringUtils.isBlank(tjzls.split(",")[x])){
					continue;
				}if("1".equals(tjzls.split(",")[x])){
					for (int i = 1;i<=4; i++) {
						productOrderDataDto.setoPhoType("0"+i);
						productOrderDataDao.addProductOrderData(productOrderDataDto);
					}
				}else{
					productOrderDataDto.setoPhoType("0"+tjzls.split(",")[x]);
					productOrderDataDao.addProductOrderData(productOrderDataDto);
				}
			}
		}
	}

	@Override
	@Transactional(rollbackFor=SQLException.class)
	public int updateProduct(ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO) throws SQLException {
		
		if(Dict.pPublicStatus_Yes_public.equals(projectDTO.getpPublicStatus())){
			
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setId(projectDTO.getId());
			projectTmp = projectDaoImpl.searchProjectByIdOrCode(projectTmp);
			
			if(!Dict.pProductStatus_need_public.equals(projectTmp.getStatus())){
				return 0;
			}
		}
		
		//修复-错误 #1137: 后台-产品结束金额未填写保存显示原募集规模后再次修改募集规模，结束金额仍然显示原来的
		//修改募集规模 ，将修改相应的设置年化及佣金的结束金额
		ProjectDTO bean = new ProjectDTO();
		bean.setId(projectDTO.getId());
		bean = projectDaoImpl.searchProjectByIdOrCode(bean);
		
		//判断募集规模是否修改
		if(bean != null && bean.getpIssuingScale()!=null && projectDTO.getpIssuingScale() !=null && bean.getpIssuingScale().compareTo(projectDTO.getpIssuingScale())!=0){
			log.info("######updateProduct pIssuingScale change ####### p_id:"+projectDTO.getId());
			Map<String,Object> map = new HashMap<String,Object> ();
			map.put("newAmount", projectDTO.getpIssuingScale());
			map.put("oldAmount", bean.getpIssuingScale());
			map.put("pid", projectDTO.getId());
			map.put("updateBy", projectDTO.getUpdateBy());
			projectAnnualRevenueDaoImpl.updateProjectAnnualRevenueByendAmount(map);
			log.info("######updateProduct pIssuingScale change ####### success!");
		}
		
		//图片类型(01:身份证正面；02：身份证反面；03：银行卡；04：打款凭条；05：签字页；06：合同封面；07手持签字页和合同封面；08：其他)
		ProductOrderDataDTO productOrderDataDto=new ProductOrderDataDTO();
		productOrderDataDto.setpType(projectDTO.getpType());
		productOrderDataDto.setpId(projectDTO.getId());
		productOrderDataDto.setUpdateBy(projectDTO.getUpdateBy());
		
		//删除所有该产品附件要求
		productOrderDataDao.delProductOrderData(productOrderDataDto);
		productOrderDataDto.setCreateBy(projectDTO.getUpdateBy());
		insertOrderData(projectDTO.getTjzls(), productOrderDataDto);
		log.info(" productOrderDataDao success!");
		
		//修改产品
		projectDaoImpl.updateProjectFull(projectDTO);
		log.info(" updateProject success!");
		
		//修改产品扩展
		projectDaoImpl.updateProjectExpand(projectExpandDTO);
		log.info(" updateProjectExpand success!");
		
		return 0;
	}
@Override
	public List<ProjectSendConfirmEmailVO> queryOutProductInfoByIds(
			Integer[] array) throws SQLException {
		return projectDaoImpl.queryOutProductInfoByIds(array);
	}
	/**
	 * 插入产品流水-订阅通知、产品信息
	 */
	@Override
	public int addProjectFlow(ProjectDTO projectDTO,int addType) throws SQLException {
		ProjectSubVO projectSubVO = new ProjectSubVO();
		projectSubVO.setCreateBy(projectDTO.getCreateBy());
		projectSubVO.setUpdateBy(projectDTO.getUpdateBy());
		projectSubVO.setpId(projectDTO.getId());
		projectSubVO.setpType(projectDTO.getpType());
		projectSubVO.setpName(projectDTO.getpName());
		projectSubVO.setpCode(projectDTO.getpCode());
		projectSubVO.setpFullName(projectDTO.getpFullName());
		projectSubVO.setNoticeType(addType + "");
		projectSubVO.setpPublicStatus(projectDTO.getpPublicStatus());
		projectSubVO.setpExpectSubscriptionAmount(projectDTO.getpExpectSubscriptionAmount());
		projectSubVO.setpAllSubscriptionAmount(projectDTO.getpAllSubscriptionAmount());
		projectSubVO.setpSubscriptionProgressInfo(projectDTO.getpRecruitmentSummary());
		projectSubVO.setpEstablishmentTime(projectDTO.getpEstablishmentTime());
		int r = 0;
		try {
			r =  projectDaoImpl.addProjectFlow(projectSubVO);
		} catch (Exception e) {
			log.error("addProjectFlow error ", e);
		}
		return r;
	}

	@Override
	public List<FpProjectRabate> getProductProfitRebateList(Integer productId)
			throws SQLException {
		return projectDaoImpl.getProductProfitRebateList(productId);
	}

	@Override
	public ProductDetailPageDTO getProductDetailViewByprice(Integer productId) throws SQLException {
		ProductDetailPageDTO pageDTO = projectDaoImpl.getProductDetailPage(productId); //获得产品信息
		Double hightRebate = new Double(0);
		Double lowRebate = new Double(100);
		if(pageDTO == null){
			
			return new ProductDetailPageDTO();
		}
		// ————订单流程改造	新增后端相关价格
		List<ProductProfitAndRebateVO> profitRebateList = getProductProfitAndRebateListByPrice(productId,pageDTO.getCorpType());
		// 返佣 预期年化 添加非空 判断  -lisu
		ProductAnnualRevenueDTO profit = projectDaoImpl.queryAnnualRevenue(productId,"l");
		profit = profit == null?new ProductAnnualRevenueDTO():profit;
		ProductAnnualRevenueDTO profitHight = projectDaoImpl.queryAnnualRevenue(productId,"h");
		profitHight = profitHight == null?new ProductAnnualRevenueDTO():profit;
		
		//产品内销返佣率为null处理
		if("01".equals(pageDTO.getCorpType())){ 
			//内销产品 佣金字段为null;
			if(profitHight!=null){
				profit.setRebate(null);
				profitHight.setRebate(null);
			}
		}else{
			for(ProductProfitAndRebateVO profitVo:profitRebateList){
				if(hightRebate<profitVo.getRebate()){
					hightRebate = profitVo.getRebate();
				}
				if(lowRebate>profitVo.getRebate()){
					lowRebate = profitVo.getRebate();
				}
			}
			profit.setRebate(String.valueOf(lowRebate));
			profitHight.setRebate(String.valueOf(hightRebate));
		}
		pageDTO.setProfitAndRebateList(profitRebateList);
		pageDTO.setProfit(profit);
		pageDTO.setProfitHight(profitHight);
		//产品内销返佣率为null处理END
		if(!profitRebateList.isEmpty()){
			ProductProfitAndRebateVO minVO = profitRebateList.get(0);
			pageDTO.setAnnualRevenueExpect(minVO.getExpectAnnualRevenue());
			if("01".equals(pageDTO.getCorpType())){
				//内销产品 佣金字段为null;
				pageDTO.setMinRebate(null);  //返利值
			}else{
				pageDTO.setMinRebate(minVO.getRebate());  //返利值
			}

		}

		//TODO 募集进度， 预约人数
		Map<String,Object> map = projectDaoImpl.queryProductBuyNumberAndAmount(productId);
		BigDecimal sumAmount = (BigDecimal)map.get("sumAmount");
		Long  num = (Long)map.get("num");
		logger.info("==>project num:"+num);
		logger.info("==>project sumAmount:"+sumAmount);
		if(sumAmount==null){
			sumAmount = new BigDecimal(0);
		}
		if(num==null){
			num = new Long(0);
		}
		logger.info("==>project allSubscriptionNum:"+pageDTO.getAllSubscriptionNum());
		logger.info("==>project allSubscriptionAmount:"+pageDTO.getAllSubscriptionAmount());

		pageDTO.setAllSubscriptionNum(num.intValue()+pageDTO.getAllSubscriptionNum());
		pageDTO.setAllSubscriptionAmount(pageDTO.getAllSubscriptionAmount());
		pageDTO.setAppointmentAmount((BigDecimal)map.get("sumAmount"));
		pageDTO.setAppointmentNumber((Long)map.get("num")); 
		return pageDTO;
	}

	@Override
	public int countProductListForQD(Map<String,Object> queryParams,Pager pager) throws SQLException {
		return projectDaoImpl.countProductListForQD(queryParams,pager);
	}

	@Override
	public List<ProductVO> queryProductListForQD(Map<String,Object> queryParams,Pager pager) throws SQLException {

		List<ProductVO>  listProduct = projectDaoImpl.queryProductListForQD(queryParams,pager);

		if(listProduct!=null&&listProduct.size()>0){
			for (int i = 0; i < listProduct.size(); i++) {
				//产品的扩展信息
				List<FpProjectRabate> rebateList = projectDaoImpl.getProductProfitRebateList(listProduct.get(i).getId());

				listProduct.get(i).setRebateList(rebateList);

				// 附件
				List<ProductAttachmentDTO>  attachmentList= projectDaoImpl.queryProductAttachments(listProduct.get(i).getId());
				listProduct.get(i).setAttachmentList(attachmentList);
			}
		}
		return listProduct;
	}

	@Override
	public List<Map<String, Object>> queryInvestOwner(String investOwnerName) throws SQLException {
		return projectDaoImpl.queryInvestOwner(investOwnerName);
	}

	@Override
	public ProductVO queryProductQDDetail(Integer pId) throws SQLException {

		ProductVO  productVO = projectDaoImpl.queryProductQDDetail(pId);

		if(productVO != null && productVO.getId() != null){

				//产品的扩展信息
				List<FpProjectRabate> rebateList = projectDaoImpl.getProductProfitRebateList(productVO.getId());
				productVO.setRebateList(rebateList);

				// 附件
				List<ProductAttachmentDTO>  attachmentList= projectDaoImpl.queryProductAttachments(productVO.getId());
				productVO.setAttachmentList(attachmentList);

		}

		return productVO;
	}


	/**
	 * 获得产品收益率，返佣 (包括销售、核心、成本)
	 * @param productId
	 * @return
	 * @throws SQLException 
	 */
	public List<ProductProfitAndRebateVO> getProductProfitAndRebateListByPrice(Integer productId,String corpType) throws SQLException{
		List<FpProjectRabate> rebateList = projectDaoImpl.getProductProfitRebateList(productId);
		List<ProductProfitAndRebateVO> retList = new ArrayList<ProductProfitAndRebateVO>(rebateList.size());
		for(FpProjectRabate rebate : rebateList){ //最低返利，收益率
			ProductProfitAndRebateVO vo = new ProductProfitAndRebateVO();
			retList.add(vo);
			vo.setExpectAnnualRevenue(rebate.getAnnualRevenue().getPAnnualRevenueExpect());
			vo.setStartAmount(rebate.getAnnualRevenue().getPStartAmount());
			vo.setEndAmount(rebate.getAnnualRevenue().getPEndAmount());
			if(!"01".equals(corpType)){
				vo.setRebate(rebate.getPRabateProfit().doubleValue());  //返利值 挂网
				vo.setSellingPrice(rebate.getpSellingPrice()); //销售价
				vo.setCorePrice(rebate.getpCorePrice()); //核心价
				vo.setCostPrice(rebate.getpCostPrice()); //成本价
				vo.setRebateIsRatio("01".equals(rebate.getPRabateType())); //返利类型
				// ————订单流程改造 增加后端价格
				if(null == rebate.getpBackRabateProfit()){
					vo.setBackRabate(new Double("0"));
				}else{
					vo.setBackRabate(rebate.getpBackRabateProfit().doubleValue());
				}
				vo.setBackSellingPrice(rebate.getpBackSellingPrice());
				vo.setCoreBackPrice(rebate.getpCoreBackPrice());
				vo.setCostBackPrice(rebate.getpCostBackPrice());
				vo.setpIsAgreement(rebate.getpIsAgreement());
			}
		}
		/**排序*/
		ProductProfitAndRebateVO comparator=new ProductProfitAndRebateVO();
		Collections.sort(retList,comparator);
		/***/
		return retList;
	}

	@Override
	public Map<String, Object>  queryPnameByCode(String pCode) throws SQLException {
		return projectDaoImpl.queryPnameByCode(pCode);
	}
}
